package org.springblade.humanResource.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.humanResource.entity.Project;
import org.springblade.humanResource.service.HumanUserService;
import org.springblade.humanResource.service.ProjectService;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/human")
@AllArgsConstructor
public class HumanResourceController {

	private ProjectService projectService;
	private HumanUserService humanUserService;

	@PostMapping("/list")
	@ApiOperation(value = "人力资源列表")
	public R<Map<String, Object>> HumanResourceList(@RequestParam(required = false) String time,//起止时间（2020-01,2020-06）（
													@RequestParam String deptName,
													@RequestParam String projectId,
													@RequestParam String userId,
													@RequestParam Integer current, @RequestParam Integer size) {

		Integer deptId=0;
		if (deptName!=null&&!"".equals(deptName)){
			List<Integer> ztDeptId = humanUserService.getZtDeptId(deptName);
			if (ztDeptId.size()==0){
				return R.data(null);
			}
			deptId=ztDeptId.get(0);
		}
		Map<String, Object> resultMap = new HashMap<>();
		Map<String, Object> parm = new HashMap<>();
		parm.put("projectId", projectId);
		parm.put("deptId", deptId);
		parm.put("userId", userId);
		String startDate = null, endDate = null;
		if (StringUtils.isNotEmpty(time) && time.length() == 13) {
			time = time.replaceAll("-", "-0");
		}
		if (StringUtils.isNotBlank(time)) {
			String[] times = time.split(",");
			startDate = times[0];
			endDate = times[1];
		}
		parm.put("startDate", startDate);
		parm.put("endDate", endDate);
		Integer currentIndex = (current - 1) * size;
		parm.put("currentIndex", currentIndex);
		Integer humanResourceCount = projectService.getHumanResourceCount(parm);
		parm.put("size", humanResourceCount);
		List<Map<String, Object>> humanResourceList = projectService.getHumanResourceList(parm);
		for (Map<String, Object> humanResourceMap : humanResourceList) {
			parm.put("pId", humanResourceMap.get("projectId"));
			List<Map<String, Object>> taskHumanList = projectService.getTaskHumanList(parm);
			StringBuilder ryxx = new StringBuilder();
			for (Map<String, Object> map : taskHumanList) {
				if (!map.isEmpty()) {
					ryxx.append(map.get("ryxx").toString());
					ryxx.append(" ");
				}
			}
			humanResourceMap.put("ryxx", ryxx.toString());
		}
		resultMap.put("humanResourceList", humanResourceList);
		resultMap.put("humanResourceCount", humanResourceCount);
		return R.data(resultMap);
	}
	@GetMapping("/BMselect")
	@ApiOperation(value = "部门筛选条件下拉框")
	public R getBMSelectData() {
		List<Map<String, Object>> deptList = projectService.getDeptList();
		return R.data(deptList);
	}

	@GetMapping("/XMselect")
	@ApiOperation(value = "项目筛选条件下拉框")
	public R getXMSelectData(@RequestParam Integer deptId) {
		Project project = new Project();
		project.setDeptid(deptId);
		List<Project> projectList = projectService.list(Wrappers.query(project));
		return R.data(projectList);
	}

	@GetMapping("/RYselect")
	@ApiOperation(value = "人员筛选条件下拉框")
	public R getRYSelectData(@RequestParam Integer projectId) {
		List<Map<String, Object>> userList = humanUserService.getRYlist(projectId);
		return R.data(userList);
	}

	@GetMapping("/statistics")
	@ApiOperation(value = "人力资源统计")
	public R getStatisticsData( String time, String deptName) {
		Integer deptId=null;
		if (deptName!=null&&!"".equals(deptName)){
			deptId= humanUserService.getZtDeptId(deptName).get(0);
		}

		Map<String, Object> resultMap = new HashMap<>();
		if (time.length() == 13) {
			time = time.replaceAll("-", "-0");
		}
		Map<String, Object> bartMap = new HashMap<>();
		List<String> xdata = new ArrayList<>();//柱状图X坐标
		List<Map<String, Object>> ydataList = new ArrayList<>();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");

		Map<String, Object> pieParm = new HashMap<>();
		pieParm.put("deptId", deptId);
		//过去一年
		if (!"".equals(time)) {
			String[] times = time.split(",");
			String startDate = times[0];
			String endDate = times[1];
			pieParm.put("startDate", startDate);
			pieParm.put("endDate", endDate);
			try {
				Calendar min = Calendar.getInstance();
				Calendar max = Calendar.getInstance();
				min.setTime(format.parse(startDate));
				min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

				max.setTime(format.parse(endDate));
				max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
				Calendar curr = min;
				while (curr.before(max)) {
					xdata.add(format.format(curr.getTime()));
					curr.add(Calendar.MONTH, 1);
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			for (int i = 12; i > 0; i--) {
				Calendar c = Calendar.getInstance();
				c.setTime(new Date());
				c.add(Calendar.MONTH, -i);
				Date y = c.getTime();
				xdata.add(format.format(y));
			}
		}
		List<String> deptNameList =new ArrayList<>();
		if (deptName==null||"".equals(deptName)){
			deptNameList=projectService.getDeptList().stream().map(map -> String.valueOf(map.get("deptName"))).collect(Collectors.toList());
		}else {
			deptNameList.add(deptName);
		}
		List<Map<String, Object>> barYData = projectService.getBarYData(xdata, deptNameList);
		for (String bmmc:deptNameList){
			List<Map<String, Object>> ydateList = barYData.stream().filter(map -> bmmc.equals(map.get("bmmc"))).collect(Collectors.toList());
			if (ydateList.size()==0) continue;
			double []arr=new double[xdata.size()];
			for (Map<String, Object> ydataMap:ydateList){
				int month = xdata.indexOf(ydataMap.get("month"));
				arr[month]=Double.valueOf(ydataMap.get("consumed").toString());
			}
			Map<String, Object> map = new HashMap<>();
			map.put("name",bmmc);
			map.put("data",arr);
			ydataList.add(map);
		}
		bartMap.put("xdata", xdata);
		bartMap.put("ydata", ydataList);
		
		List<Map<String, Object>> piedata = projectService.getPieData(pieParm);
		List<Map<String, Object>> monthUserHourRank = projectService.getMonthUserHourRank(pieParm);
		List<Map<String, Object>> userFreeRank = projectService.getUserFreeRank(pieParm);

		resultMap.put("barData", bartMap);
		resultMap.put("pieData", piedata);
		resultMap.put("monthUserHourRank", monthUserHourRank);
		resultMap.put("userFreeRank", userFreeRank);
		return R.data(resultMap);
	}

	@GetMapping(value = "/deptSelectByUser")
	@ApiOperation(value = "人力资源用户部门下拉框")
	public R<List<HashMap<String, Object>>> getDeptSelectByUser(BladeUser bladeUser) {
		return R.data(humanUserService.getDeptSelectByUser(bladeUser));
	}

	@GetMapping(value = "/personnelByUser")
	public R<List<HashMap<String, Object>>> getPersonnelByUser(@RequestParam(required = false) String projectId, BladeUser bladeUser) {
		return R.data(humanUserService.getPersonnelByUser(bladeUser, projectId));
	}
	/**
	 * 导出人力资源
	 */
	@GetMapping("/export")
	@ApiOperation(value = "导出", notes = "筛选条件")
		public void export(HttpServletRequest request,HttpServletResponse response, @RequestParam String time, String deptId, String projectId, String userId) throws IOException {
//			查询列表

		//处理oa系统和禅道系统部门数据对应不一致问题
		if ("4".equals(deptId)) {
			deptId = "1";
		} else if ("5".equals(deptId)) {
			deptId = "2";
		} else if ("6".equals(deptId)) {
			deptId = "4";
		} else {

		}
		Map<String, Object> parm = new HashMap<>();
		parm.put("deptId", deptId);
		parm.put("projectId", projectId);
		parm.put("userId", userId);
		String startDate = null, endDate = null;
		if (StringUtils.isNotEmpty(time) && time.length() == 13) {
			time = time.replaceAll("-", "-0");
		}
		if (StringUtils.isNotBlank(time)) {
			String[] times = time.split(",");
			startDate = times[0];
			endDate = times[1];
		}
		parm.put("startDate", startDate);
		parm.put("endDate", endDate);

		HSSFWorkbook workbook = humanUserService.export(parm, response);
		//准备将Excel的输出
		//流通过response输出到页面下载
		//八进制输出流
		//response.setContentType("application/octet-stream");
		//这后面可以设置导出Excel的名称，此例中名为费用报销单报销.xls
		//response.setHeader("Content-disposition", "attachment;filename=人力资源月报.xls");

		String agent = request.getHeader("USER-AGENT").toLowerCase();
		response.setContentType("application/vnd.ms-excel");
		String fileName = "人力资源月报";
		String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
		if (agent.contains("firefox")) {
			response.setCharacterEncoding("utf-8");
			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls" );
		} else {
			response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
		}
		//刷新缓冲
		response.flushBuffer();
		//workbook将Excel写入到response的输出流中，供页面下载
		workbook.write(response.getOutputStream());
	}

}
